<?php
/**
 * Created by PhpStorm.
 * User: simon
 * Date: 2016/11/24
 * Time: 10:11
 */

namespace App\Weixin;


use Illuminate\Cache\FileStore;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use p5\objects\ArrayUtils;

class WeixinConfigHelper
{

    public static function initIndustry($companyId, $clearCache = false)
    {
        $cacheKey = self::makeCacheKey("industries", $companyId);
        if ($clearCache == true) {
            self::deleteCache($cacheKey);
        }
        $industries = self::getCache($cacheKey);
        $client = WechatClientFactory::newClient($companyId);
        if (empty($industries)) {
            Log::debug("$companyId 行业设置未知");
            $industries = $client->getTMIndustry();
        }

        if (!is_array($industries)) {
            Log::error("获取 $companyId 的行业信息出错了!");
            return false;
        }
        $configIndustries = Config::get("wxinit.industries");
        $configIndustryValues = array_values($configIndustries);
        $needModify = false;
        if (!array_key_exists("secondary_industry", $industries)) {
            $needModify = true;
        } else if (!array_key_exists("second_class", $industries["secondary_industry"])) {
            $needModify = true;
        } else if ($industries["secondary_industry"]["second_class"] != $configIndustryValues[1]) {
            $needModify = true;
        } else if (!array_key_exists("second_class", $industries["primary_industry"])) {
            $needModify = true;
        } else if ($industries["primary_industry"]["second_class"] != $configIndustryValues[0]) {
            $needModify = true;
        }
        if ($needModify) {
            $keys = array_keys($configIndustries);
            Log::debug("重新设置 $companyId 的行业");
            $client->setTMIndustry($keys[0], $keys[1]);
            //重新获取行业信息
            $industries = $client->getTMIndustry();
            self::setCache($cacheKey, $industries);
        } else {
            Log::debug("将 $companyId 的行业设置保存到本地文件缓存");
            self::setCache($cacheKey, $industries);
        }

        return $industries;
    }

    public static function getTemplateIdByName($companyId, $name)
    {
        $cacheKey = self::makeCacheKey("templates", $companyId);
        $templates = self::getCache($cacheKey);
        $client = WechatClientFactory::newClient($companyId);
        $resetCache = false;
        if (empty($templates)) {
            Log::debug("从微信接口读取 $companyId 的模板消息配置信息");
            $templates = $client->getTMTemplates();
            if (!is_array($templates)) {
                $resetCache = true;
            }
        }
        if (!is_array($templates)) {
            Log::error("获取 $companyId 的模板消息配置出错了!");
            return "";
        }
        // 返回格式参考 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN
        $id = self::findTemplateId($templates, $name);
        if ($id === false) {
            Log::error("company $companyId 尚未配置模板 $name !");
            $code = self::getTemplateCode($name);
            if ($code === false) {
                Log::error("company $companyId 无效的模板名称: $name !");
                return "";
            }
            if ($client->addTemplateMessage($code)) {
                // 重新查询转换
                $templates = $client->getTMTemplates();
                $id = self::findTemplateId($templates, $name);
                if ($id !== false) {
                    $resetCache = true;
                }
            } else {
                Log::debug(json_encode($client->errMsg));
                Log::error("company $companyId 添加消息模板 $name ($code) 失败!");
            }
        }
        if ($resetCache) {
            self::setCache($cacheKey, $templates);
        }
        return $id;

    }

    private static function getTemplateCode($name)
    {
        $configTemplates = Config::get("wxinit.templates");
        foreach ($configTemplates as $key => $value) {
            if ($value == $name) {
                return $key;
            }
        }
        return false;
    }

    private static function findTemplateId($templates, $name)
    {
        $list = $templates["template_list"];
        $item = ArrayUtils::find($list, "title", $name);
        if (empty($item)) {
            return false;
        }
        return $item["template_id"];
    }


    public static function getCache($key)
    {
        $fs = self::getFileStore();
        $object = $fs->get($key);
        if (!empty($object)) {
            Log::debug("从本地缓存中获取配置信息 $key = " . json_encode($object));
        }
        return $object;
    }

    public static function deleteCache($key)
    {
        $fs = self::getFileStore();
        $fs->forget($key);
    }

    public static function setCache($key, $value, $minutes = 0)
    {
        $fs = self::getFileStore();
        if ($minutes <= 0) {
            $fs->forever($key, $value);
        } else {
            $fs->put($key, $value, $minutes);
        }
    }

    public static function getFileStore()
    {
        $object = Storage::disk("weixin");
        // echo get_class($object);
        $fs = new Filesystem($object);
        $fileStore = new FileStore($fs, "configs");
        return $fileStore;
    }

    public static function makeCacheKey($flag, $companyId)
    {
        return $companyId . ":" . $flag;
    }
}